// fill the sell drop down stock selector or hide it
const sellStockForm =  document.getElementById("sellStockForm"); 
const sellStockSelector = document.getElementById("sellStockSelector");
function fillStockSellSelect(values) {
  // hide if doesnt own stocks
  if (values === undefined || Object.keys(values).length == 0) {
    sellStockForm.hidden = true;
  } else {
    sellStockForm.hidden = false;
  }

  delete values["_all"];
  var options = [];
  for (stock in values) {
    options.push(document.createElement("option"));
    options[options.length-1].setAttribute("value", stock); 
    options[options.length-1].textContent = stock; 
  }
  // clear all old options
  while (sellStockSelector.options.length > 0) sellStockSelector.remove(0);

  // push all to the selector
  options.forEach(function (item) { sellStockSelector.appendChild(item); });
}


async function sellStocks(buyOneOf = undefined) {
  // show loading
  showLoading();

  const sellStock = new FormData(sellStockForm),
        buyStockXHR = new XMLHttpRequest();
  if (buyOneOf) {
    sellStock.set("amountStocks", 1);
    sellStock.set("stockSymbol", buyOneOf);
  }
  buyStockXHR.addEventListener( 'load', function(event) {
    // DBG: alert("Aktien erfolgreich verkauft. Aktualisiere..");
    // update
    setNewStocks();
  } );

  buyStockXHR.addEventListener('error', function(event) {
    alert("Ein Fehler trat auf. Versuchen Sie es erneut.");
    // still update - this doesnt cause issues but possibly avoids
    // desync if the update came still through somehow
    setNewStocks();

  } );

  buyStockXHR.open("POST", "sellStocks");
  buyStockXHR.send(sellStock);
}

const func_sellStocks = async function (event) {
  event.preventDefault();
  sellStocks();
}
sellStockForm.addEventListener("submit", func_sellStocks, true);

